﻿using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;

namespace TestMef
{
    public static class Mef2
    {
        #region 属性  
        private static  CompositionContainer _container { get; set; }
        private static readonly string AppExecuteRootDir;//程序执行主目录，对于网站就是BIN。
        public static HashSet<string> ExportedDlls;


        #endregion

        #region 构造

        /// <summary>
        /// 静态构造函数
        /// </summary>
        static Mef2()
        {
            AppExecuteRootDir = AppDomain.CurrentDomain.BaseDirectory;
            ExportedDlls = new HashSet<string>();
        }

        #endregion

        public static void AddMefContainer(this IServiceCollection services)
        { 
            // An aggregate catalog that combines multiple catalogs.
            var catalog = new AggregateCatalog();
            // Adds all the parts found in the same assembly as the Program class.
            catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));

            // Create the CompositionContainer with the parts in the catalog.
            _container = new CompositionContainer(catalog);
            _container.ComposeParts(services);
        }
         

        #region 获取实例    


        public static T GetService<T>()
        {
            return _container.GetExportedValue<T>();
        }
        /// <summary>
        /// 注意释放
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public static T GetService<T>(string key)
        {
            return _container.GetExportedValue<T>(key);
        }


        public static IEnumerable<T> GetServices<T>()
        {
            return _container.GetExportedValue<IEnumerable<T>>();
        }

        public static IEnumerable<T> GetServices<T>(string key)
        {
            return _container.GetExportedValues<T>(key);
        }

        

        #endregion
    }
}
